package com.tianpengtech.common.apidoc;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.tianpengtech.common.generator.app.Generator;
import com.tianpengtech.common.util.EngineUtil;

public class DocInterceptor implements Interceptor {

	public boolean isBuildDoc = true;// 是否立即在请求之后生成文档信息

	@Override
	public void intercept(Invocation inv) {
		inv.invoke();
		Object ret = inv.getReturnValue();
		Controller c = inv.getController();
		if (isBuildDoc) {
			generateApi(inv, ret, c);
		}
		c.renderJson(ret);
	}

	private void generateApi(Invocation inv, Object ret, Controller c) {

		try {
			outPutDoc(builderApiParam(inv, c));
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	private String docTitle(String title) {

		return "xxxx系统" + title + "方法接口信息";
	}

	private ApiBean builderApiParam(Invocation inv, Controller c) throws InstantiationException, IllegalAccessException {
		Method method = inv.getMethod();
		String clazzStr = c.getClass().getSimpleName();
		ApiBean apiBean = new ApiBean(docTitle(clazzStr+"-"+method.getName()), "v1.0");
		Object ret = inv.getReturnValue();
		apiBean.setAction(inv.getActionKey());
		apiBean.setMethod(c.getRequest().getMethod());
		apiBean.setResult(JsonKit.toJson(ret));
		apiBean.setClazz(clazzStr);
		List<ApiParamItem> ApiParamItem = new ArrayList<ApiParamItem>();
		Parameter[] params = method.getParameters();
		ApiDescrition descrition = method.getDeclaredAnnotation(ApiDescrition.class);
		if (descrition != null) {
			apiBean.setDescript(descrition.descript());
		}

		for (Parameter each : params) {
			if (each != null) {
				Class<?> clazz = each.getType();
				Class<?> superClass = clazz.getSuperclass();
				if (superClass != null) {
					if (clazz.newInstance() instanceof Model) {
						Para para = each.getAnnotation(Para.class);
						if (para != null) {
							String profix = (String) para.value();
							Model<?> model = (Model<?>) c.getModel(clazz, profix);
							for (Entry<String, Object> parameter : model._getAttrsEntrySet()) {
								if (StrKit.isBlank(profix)) {
									ApiParamItem.add(new ApiParamItem(parameter.getKey(), parameter.getValue() + ""));
								} else {
									ApiParamItem.add(new ApiParamItem(profix + "." + parameter.getKey(),
											parameter.getValue() + ""));
								}
							}
						}
					}
				} else {
					ApiParamItem.add(new ApiParamItem(each.getName(), c.getPara(each.getName())));
				}
			}
		}
		apiBean.setApiParams(ApiParamItem);
		return apiBean;
	}

	private void outPutDoc(ApiBean apiBean) {
		String content = EngineUtil.readFileContent("front/doc/doc-view.html", Kv.by("apiBean", apiBean));
		System.out.println(content);
		String apiDocName = apiBean.getName();
		Generator.createFile("xxxx系统接口API文档",apiDocName+".md", "/Users/tianpengtech/Documents/export", content);
	}

}
